package com.gaussic.controller;

/**
 * Created by IPE on 2017/1/5.
 */

import com.gaussic.model.UserEntity;
import com.gaussic.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 登录认证的控制器
 */
@Controller
public class LoginControl {
    // 自动装配数据库接口，不需要再写原始的Connection来操作数据库
    @Autowired
    UserRepository userRepository;

    @RequestMapping(value = "/logining", method = RequestMethod.POST)
    public String userLoginPost(@ModelAttribute("user") UserEntity userEntity,HttpServletRequest request) {
        // 注意此处，post请求传递过来的是一个UserEntity对象，里面包含了该用户的信息
        // 通过@ModelAttribute()注解可以获取传递过来的'user'，并创建这个对象

        if(userEntity.getPassword()==null||userEntity.getNickname()==null){
            return "redirect:/login";
        }

        UserEntity r=userRepository.findByNickname(userEntity.getNickname());

        if(r.getPassword().equals(userEntity.getPassword())){
            HttpSession s=request.getSession();
            s.setAttribute("username",r.getNickname());
            return "redirect:/";
        }

        return "redirect:/login";
    }
    /**
     * 登录
     * @param session
     * 			HttpSession
     * @param username
     * 			用户名
     * @param password
     * 			密码
     * @return
     */
    @RequestMapping(value="/login")
    public String login(HttpSession session, String username, String password) throws Exception{
        //在Session里保存信息
        session.setAttribute("username", username);
        //重定向
        return "login";
    }

    /**
     * 退出系统
     * @param session
     * 			Session
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/logout")
    public String logout(HttpSession session) throws Exception{
        //清除Session
        session.invalidate();

        return "redirect:/";
    }



}

